$(document).ready(function(){ 
  nuggets.setFocusMagicOnTextInputs();
  nuggets.autocomplete.init($('.fb-search'));
});


var nuggets = {
    loadedLists: {},
    
    autocomplete: {
        
        isVisible: function() {
            var container = $('#auto-complete-container');
            return container.is(':visible');
        },
        
        init: function(elem) {
            elem.keyup(function(evt) {
                var container = $('#auto-complete-container');
                var self = $(this);
                nuggets.autocomplete.targetInput = self;
                var currVal = self.val();
                if (container.is(':visible')) {
                    if (evt.keyCode == 40) { // down
                        nuggets.autocomplete.selectNext();
                        return;
                    } else if (evt.keyCode == 38) { // up
                        nuggets.autocomplete.selectPrevious();
                        return;
                    } else if (evt.keyCode == 13) { // enter
                        nuggets.autocomplete.selectResult(currVal);                        
                        return;
                    }               
                }
                if (nuggets.autocomplete.searchTerm == currVal) return;
                nuggets.autocomplete.searchTerm = currVal;            

                nuggets.autocomplete.checkAndClearTimeout();

                // set a timeout before doing api call so can minimize async requests
                nuggets.autocomplete.searchTimeout = window.setTimeout(function() {
                    FB.api('/search', {q: nuggets.autocomplete.searchTerm, type: 'page', limit: 5}, function(res) {
                        nuggets.autocomplete.searchData = res.data;
                        var s = parseTemplate($("#AutoCompleteTemplate").html(), { pages: nuggets.autocomplete.searchData } );                    
                        container.html(s);
                        container.css('left', self.position().left);
                        container.css('top', self.position().top + 21);                        
                        
                        container.show();
                        
                        nuggets.autocomplete.setBodyClickListener();
                        
                    });
                }, 300);


            });
        },
        
        checkAndClearTimeout: function() {
            if (nuggets.autocomplete.searchTimeout) {
                window.clearTimeout(nuggets.autocomplete.searchTimeout);
                nuggets.autocomplete.searchTimeout = null;
            }
        },
        
        setBodyClickListener: function() {
            var body = $(document.body);
            body.click(function(evt) {
                // hack to prevent this getting called when press enter key (strange!)
                if (evt.clientX == 0 && evt.clientY == 0) return;
                nuggets.autocomplete.hide();
                body.unbind('click');
            });
        },
        
        selectNext: function() {
            var container = $('#auto-complete-container');
            var selected = container.find('.result.selected');
            if (selected.length == 0) {
                // select first one
                $(container.find('.result')[0]).addClass('selected');
            } else {
                selected.removeClass('selected');
                var next = selected.next();
                if (next) {
                    next.addClass('selected')                    
                }
            }
        },
        
        selectPrevious: function() {
            var container = $('#auto-complete-container');
            var selected = container.find('.result.selected');
            if (selected.length == 0) {
                // select last one
                var results = container.find('.result');
                $(results[results.length - 1]).addClass('selected');
            } else {
                selected.removeClass('selected');
                var prev = selected.prev();
                if (prev) {
                    prev.addClass('selected')                    
                }
            }
        },
        
        clickResult: function(elem) {
            var selected = $(elem);
            nuggets.autocomplete._processResult(selected);
        },
        
        selectResult: function(currVal) {
            var container = $('#auto-complete-container');
            var selected = container.find('.result.selected');
            nuggets.autocomplete._processResult(selected, currVal);
        },
        
        _processResult: function(selected, currVal) {
            var res;
            if (selected.length == 0) {
                // none selected, just use search query
                res = currVal;
            } else {
                res = nuggets.autocomplete.searchData[parseInt(selected.attr('index'))].name;
            }
            nuggets.autocomplete.hide();
            nuggets.autocomplete.targetInput.val(res);
            nuggets.autocomplete.targetInput.parent('form').submit();
        },
        
        hide: function() {
            var container = $('#auto-complete-container');
            container.html('');
            container.hide();
        }
    },
    
    
    
    setFocusMagicOnTextInputs: function(parent) {
        if (!parent) {
            parent = document.body;
        }            
        var elems = $(parent).find('input[type=text]')
        elems.focus(function(){ 
            if($(this).val() == $(this).attr('defaultValue')) {
              $(this).val('');
              $(this).removeClass('gray');
            }
        });

        elems.blur(function(){
            if($(this).val() == '') {
              $(this).val($(this).attr('defaultValue'));
              $(this).addClass('gray');      
            } 
        });
        for (var i = 0; i < elems.length; i++) {
            var elem = $(elems[i]);
            if (elem.hasClass('autocomplete')) {
                nuggets.autocomplete.init(elem);
            }
        }
        
    },
    onListSelectChange: function(elem) {
        var selectedValue = elem.options[elem.selectedIndex].value;
        var newListDiv = $('#name-new-list');
        if (selectedValue == 'create') {
            newListDiv.show();
        } else {
            newListDiv.hide();
        }
        $('#name-new-list input').focus();
    },
    
    expandList: function(key) {
        if (!nuggets.loadedLists[key]) {
            $.ajax({
              url: "expandList",
              data: {listKey: key},
              success: function(res) {
                  nuggets.loadedLists[key] = true;
                  var container = $('#list-items-' + key);
                  container.html(res);
                  $('#list-items-container-' + key).show();
                  $('#expand-link-' + key).html('less');
                  nuggets.setFocusMagicOnTextInputs(container);
              }
             });
        } else {
            var elem = $('#list-items-container-' + key).toggle();
            $('#expand-link-' + key).html(elem.is(":visible") ? 'less' : 'more');
        }
    },
    
    createListItem: function(elem) {
        if (nuggets.autocomplete.isVisible()) return;
        nuggets.autocomplete.checkAndClearTimeout();
        var formJQ = $(elem);
        var listKey = formJQ.find('input[name="listKey"]').val();
        var params = {comment: formJQ.find('input[name="comment"]').val(),
               listKey: listKey};
        $.ajax({
            url: 'create',
            data: params,
            type: 'POST',
            success: function(res) {
                var container = $('#list-items-' + listKey);
                container.html(res);
                nuggets.setFocusMagicOnTextInputs(container);
            }
        })
    },
    
    createList: function(elem) {
        var formJQ = $(elem);
        var params = {newList: formJQ.find('input[name="newList"]').val()};
        $.ajax({
            url: 'createList',
            data: params,
            type: 'POST',
            success: function(res) {
                var replaceMe = formJQ.closest('#create-new-list-form');
                replaceMe.replaceWith(res);
                nuggets.setFocusMagicOnTextInputs();
            }
        })
    }
};